pagetutor.com - HTML tutorials for the rest of us

Javascript Tutor - Lesson 2

Variables.

What's a variable? Let's suppose x=5.

x is a variable. At the time of the statement, x happens to be 5. Can x be something else? Sure, x=6. Now x equals 6. (Hence the name "variable"... it's value can vary.)

Can a variable be something other than a number? Sure. How about x="Joe". Now x equals the string "Joe". (A string by the way is a string of characters).

Can the name of a variable be something other than a letter like x? Sure, myname="Joe". Simple.

How can we incorporate this new found knowledge into our function? Easy...

<HTML>
<HEAD>
<TITLE></TITLE>

<SCRIPT language="javascript"><!--

function HelloWorld()
{
   myname = "Joe";
   alert (myname);
}

//--></SCRIPT>

</HEAD>
<BODY>

<A HREF="javascript:HelloWorld()">Hello</A>

</BODY>
</HTML>

Try it.

(Note the first example had quotes around the string in the alert command*, but when we used a variable, there were no quotes.)

*Technically it's the alert method, but we'll get into that later. Command is fine for now and is probably a better description anyway :-)

We could make it say Hello + variable...

<HTML>
<HEAD>
<TITLE></TITLE>

<SCRIPT language="javascript"><!--

function HelloWorld()
{
   myname = "Joe";
   alert ("Hello " + myname);
}

//--></SCRIPT>

</HEAD>
<BODY>

<A HREF="javascript:HelloWorld()">Hello</A>

</BODY>
</HTML>

Try it.

<< BACK         NEXT >>
pagetutor.com



Invest in the future - Hug your kid today.